# 多个小球
import pygame
import sys
import random

# 初始化Pygame
pygame.init()

# 设置窗口大小
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))

# 设置标题
pygame.display.set_caption("多彩小球游戏")

# 定义颜色列表
colors = [
    (255, 0, 0),   # Red
    (0, 255, 0),   # Green
    (0, 0, 255),   # Blue
    (255, 255, 0), # Yellow
    (255, 0, 255), # Magenta
    (0, 255, 255), # Cyan
    (128, 0, 128)  # Purple
]

# 小球的位置、速度和半径
balls = []
num_balls = 5
for _ in range(num_balls):
    ball_radius = random.randint(10, 20)
    ball_pos = [random.randint(ball_radius * 2, screen_width - ball_radius * 2),
                random.randint(ball_radius * 2, screen_height - ball_radius * 2)]
    ball_speed = [random.choice([-2, -1, 1, 2]), random.choice([-2, -1, 1, 2])]
    balls.append({'pos': ball_pos, 'speed': ball_speed, 'radius': ball_radius, 'color': random.choice(colors)})

# 游戏主循环
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # 更新每个小球的位置
    for ball in balls:
        ball['pos'][0] += ball['speed'][0]
        ball['pos'][1] += ball['speed'][1]

        # 检查小球是否碰撞到窗口边界
        if ball['pos'][0] < 0 or ball['pos'][0] > screen_width - ball['radius'] * 2:
            ball['speed'][0] = -ball['speed'][0]
        if ball['pos'][1] < 0 or ball['pos'][1] > screen_height - ball['radius'] * 2:
            ball['speed'][1] = -ball['speed'][1]

    # 填充背景颜色
    screen.fill((255, 255, 255))

    # 绘制所有小球
    for ball in balls:
        pygame.draw.circle(screen, ball['color'], ball['pos'], ball['radius'])

    # 更新屏幕显示
    pygame.display.flip()

    # 控制游戏帧率
    pygame.time.delay(10)

# 清理并退出Pygame
pygame.quit()
sys.exit()